import type { Camera } from "../Camera";
import { GNode } from "../GNode";
/**
 * 拖尾效果，跟随父节点移动，并渲染拖尾效果。

 */
export class Tail extends GNode{

    color:string = "#000"
    frames:{x:number,y:number}[] = []
    tailWidth:number = 10
    colorRgba:number[] = []

    update(deltaTime: number): void {
        this.frames.unshift({x:this.parent!.position.x,y:this.parent!.position.y})
        if(this.frames.length > 10) {
            this.frames.pop()
        }
    }
    render(context: CanvasRenderingContext2D, camera: Camera): void {
        if(this.frames.length < 2) {
            return
        }
        console.log(1);
        
        context.beginPath();
        let last = this.frames[this.frames.length - 1]
        let now = this.frames[0]
        if(last.x===now.x && last.y===now.y) {
            //动作太快首尾确实相连了呢？
            return
        }
        //todo 圆滑  可以用贝塞尔曲线
        let gradient = context.createLinearGradient( now.x, now.y,last.x, last.y);
        let frameSize = this.frames.length
        if(this.colorRgba.length === 0)  {
            this.colorRgba = getRGBA(this.color,context)
        }
        //渐变插值
        for(let i = 0;i<=frameSize;i++) {
            gradient.addColorStop(i/frameSize, `rgba(${this.colorRgba[0]},${this.colorRgba[1]},${this.colorRgba[2]},${(frameSize-i)/frameSize})`);
        }
        gradient.addColorStop(0, this.color);
        gradient.addColorStop(1, "rgba(0, 0, 0, 0)");
        context.lineWidth = this.tailWidth;
        context.moveTo(now.x, now.y);
        for(let i = 1;i<this.frames.length;i++) {
            let frame = this.frames[i]
            context.lineTo(frame.x, frame.y);
        }
        context.strokeStyle = gradient;
        context.stroke();
    }
}

export function getRGBA(color: string, context: CanvasRenderingContext2D): [number, number, number, number] {
    // Create temporary canvas
    // const canvas = document.createElement('canvas');
    // canvas.width = 1;
    // canvas.height = 1;
    // const ctx = canvas.getContext('2d');
    
    // if (!ctx) {
    //   throw new Error('Could not create canvas context');
    // }
  
    // Set fill style to color
    context.fillStyle = color;
    context.fillRect(0, 0, 1, 1);
  
    // Get pixel data
    const imageData = context.getImageData(0, 0, 1, 1);
    const data = imageData.data;
  
    // Return RGBA values
    return [data[0], data[1], data[2], data[3]];
  }